<?php

namespace app\admin\Controller;

use app\admin\Model\ReasonModel;
use cmf\controller\AdminBaseController;
use think\db\Where;
use think\Validate;

class ReasonController extends AdminBaseController
{
    public function index () {
        extract(input());
        $where = new Where;
        if(isset($reason) && !empty($reason)){
            $where['reason'] = ['like','%'.$reason.'%'];
        }
        $data = ReasonModel::where($where)->order('id Desc')
            ->paginate(3,false,['query'=>input()]);
        $page = $data->render();
        return $this->fetch('',[
            'data' => $data,
            'page' => $page
        ]);
    }
    public function add() {
        return $this->fetch();
    }
    public function addPost() {
        $data = input();
        $rule = [
            'reason' => 'require',
        ];
        $msg = [
            'reason.require' => '扣分原因不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
        $add = ReasonModel::create($data);
        if ($add){
            return json(['code' => 1 ,'msg' => '添加成功']);
        }else{
            return json (['code' => 2 ,'msg' => '添加失败']);
        }
    }
    public function edit(){
        $id = input('id');
        $data = ReasonModel::where('id',$id)->find();
        $this->assign('data',$data);
        $this->assign('id',$id);
        return $this->fetch();
    }
    public function editPost(){
        $data = input();
        $rule = [
            'reason'  => 'require',
        ];
        $msg = [
            'reason.require' => '扣分原因不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result   = $validate->check($data);
        if (true!==$result){
            $this->error($validate->getError());
        }
        $edit = ReasonModel::where('id',$data['id'])->update($data);
        if($edit){
            $this->success('修改成功','reason/index');
        }else{
            $this->error('修改失败','reason/index');
        }
    }
    public function delete () {
        $id = input('id');
        $del = ReasonModel::destroy($id);
        if($del){
            $this->success('删除成功','reason/index');
        }else{
            $this->error('删除失败','reason/index');
        }
    }
    public function delAll() {
        $ids = input('ids/a');
        $del = ReasonModel::destroy($ids);
        if($del){
            $this->success('删除成功','reason/index');
        }else{
            $this->error('删除失败','reason/index');
        }
    }
}